package xju.rjxy.shop.web.controller;

import xju.rjxy.shop.common.framework.simplemvc.RequestMapping;
import xju.rjxy.shop.common.utils.JSONUtil;
import xju.rjxy.shop.common.utils.Result;
import xju.rjxy.shop.model.domain.CommunityPost;
import xju.rjxy.shop.service.ICommunityService;
import xju.rjxy.shop.service.impl.CommunityServiceImpl;
import xju.rjxy.shop.utils.JDBCUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/community")
public class CommunityController {
    
    private final ICommunityService communityService = new CommunityServiceImpl();
    
    /**
     * GET /api/community/game-list.do
     * 查询所有 flag=2 AND deleted=0 的游戏，返回 id 和 game_name
     * 返回结构：{ code, msg, data }
     */
    @RequestMapping("/game-list.do")
    public void getGameList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        try (Connection conn = JDBCUtils.getConnection()) {
            String sql = "SELECT id, game_name FROM games WHERE flag=2 AND deleted=0 ORDER BY id ASC";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<>();
                    row.put("id", rs.getInt("id"));
                    row.put("game_name", rs.getString("game_name"));
                    data.add(row);
                }
            }
            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", data);
        } catch (SQLException e) {
            result.put("code", 500);
            result.put("msg", "数据库异常: " + e.getMessage());
            result.put("data", null);
        }
        response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
    }
    
    /**
     * GET /api/community/post-list.do?game_id=xxx
     * 查询 community_posts 表所有该游戏的帖子，返回结构同上
     */
    @RequestMapping("/post-list.do")
    public void getPostList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        String gameIdStr = request.getParameter("game_id");
        if (gameIdStr == null || gameIdStr.trim().isEmpty()) {
            result.put("code", 400);
            result.put("msg", "参数 game_id 缺失");
            result.put("data", null);
            response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
            return;
        }
        int gameId;
        try {
            gameId = Integer.parseInt(gameIdStr);
        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "参数 game_id 格式错误");
            result.put("data", null);
            response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
            return;
        }
        try (Connection conn = JDBCUtils.getConnection()) {
            String sql = "SELECT id, user_id, title, content, create_time FROM community_posts WHERE game_id=? AND flag=2 AND deleted=0 ORDER BY create_time DESC";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setInt(1, gameId);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<>();
                    row.put("id", rs.getInt("id"));
                    row.put("user_id", rs.getInt("user_id"));
                    row.put("title", rs.getString("title"));
                    row.put("content", rs.getString("content"));
                    row.put("create_time", rs.getTimestamp("create_time"));
                    data.add(row);
                }
            }
            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", data);
        } catch (SQLException e) {
            result.put("code", 500);
            result.put("msg", "数据库异常: " + e.getMessage());
            result.put("data", null);
        }
        response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
    }

    /**
     * GET /api/community/post-detail-list.do?game_id=xxx
     * 查询 community_posts 表所有该游戏的帖子，返回 id, game_id, title, content, video_url, images, create_time，按 create_time DESC 排序
     * 返回结构：{ code, msg, data }
     */
    @RequestMapping("/post-detail-list.do")
    public void getCommunityPostDetailList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        String gameIdStr = request.getParameter("game_id");
        if (gameIdStr == null || gameIdStr.trim().isEmpty()) {
            result.put("code", 400);
            result.put("msg", "参数 game_id 缺失");
            result.put("data", null);
            response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
            return;
        }
        int gameId;
        try {
            gameId = Integer.parseInt(gameIdStr);
        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "参数 game_id 格式错误");
            result.put("data", null);
            response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
            return;
        }
        try (Connection conn = JDBCUtils.getConnection()) {
            String sql = "SELECT p.id, p.game_id, p.user_id, u.username, p.title, p.content, p.video_url, p.images, p.create_time " +
                         "FROM community_posts p JOIN users u ON p.user_id = u.id " +
                         "WHERE p.game_id=? AND p.flag=2 AND p.deleted=0 AND u.deleted=0 " +
                         "ORDER BY p.create_time DESC";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setInt(1, gameId);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<>();
                    row.put("id", rs.getInt("id"));
                    row.put("game_id", rs.getInt("game_id"));
                    row.put("user_id", rs.getInt("user_id"));
                    row.put("username", rs.getString("username"));
                    row.put("title", rs.getString("title"));
                    row.put("content", rs.getString("content"));
                    row.put("video_url", rs.getString("video_url"));
                    row.put("images", rs.getString("images"));
                    row.put("create_time", rs.getTimestamp("create_time"));
                    data.add(row);
                }
            }
            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", data);
        } catch (SQLException e) {
            e.printStackTrace(); // 新增详细异常日志
            result.put("code", 500);
            result.put("msg", "数据库异常: " + e.getMessage());
            result.put("data", null);
        } catch (Exception e) {
            e.printStackTrace(); // 捕获并打印所有异常
            result.put("code", 500);
            result.put("msg", "服务器异常: " + e.getMessage());
            result.put("data", null);
        }
        response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
    }
    
    /**
     * 发布社区帖子
     * POST /api/community/post-create.do
     * 请求参数：JSON，所有字段必填
     * 返回结构：{ code, msg, data }
     */
    @RequestMapping("/post-create.do")
    public void postCreate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        String line;
        try (BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        com.alibaba.fastjson.JSONObject json;
        try {
            json = com.alibaba.fastjson.JSON.parseObject(sb.toString());
        } catch (Exception e) {
            result.put("code", 400);
            result.put("msg", "参数缺失或格式错误");
            result.put("data", null);
            response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
            return;
        }
        // 校验参数
        Integer gameId = json.getInteger("game_id");
        Integer userId = json.getInteger("user_id");
        String title = json.getString("title");
        String content = json.getString("content");
        Integer flag = json.getInteger("flag");
        Integer deleted = json.getInteger("deleted");
        String createTime = json.getString("create_time");
        String updateTime = json.getString("update_time");
        if (gameId == null || userId == null || title == null || content == null || content.trim().isEmpty() || flag == null || deleted == null || createTime == null || updateTime == null
            || flag != 2 || deleted != 0) {
            result.put("code", 400);
            result.put("msg", "参数缺失或格式错误");
            result.put("data", null);
            response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
            return;
        }
        // 插入数据库
        try (Connection conn = JDBCUtils.getConnection()) {
            String sql = "INSERT INTO community_posts (game_id, user_id, title, content, flag, deleted, create_time, update_time) VALUES (?, ?, ?, ?, 2, 0, ?, ?)";
            try (PreparedStatement ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
                ps.setInt(1, gameId);
                ps.setInt(2, userId);
                ps.setString(3, title);
                ps.setString(4, content);
                ps.setString(5, createTime);
                ps.setString(6, updateTime);
                int affected = ps.executeUpdate();
                if (affected == 1) {
                    ResultSet rs = ps.getGeneratedKeys();
                    int newId = -1;
                    if (rs.next()) {
                        newId = rs.getInt(1);
                    }
                    // 返回新插入的帖子详情
                    Map<String, Object> data = new HashMap<>();
                    data.put("id", newId);
                    data.put("game_id", gameId);
                    data.put("user_id", userId);
                    data.put("title", title);
                    data.put("content", content);
                    data.put("flag", 2);
                    data.put("deleted", 0);
                    data.put("create_time", createTime);
                    data.put("update_time", updateTime);
                    result.put("code", 200);
                    result.put("msg", "success");
                    result.put("data", data);
                } else {
                    result.put("code", 500);
                    result.put("msg", "数据库异常: 插入失败");
                    result.put("data", null);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "数据库异常: " + e.getMessage());
            result.put("data", null);
        }
        response.getWriter().write(new com.alibaba.fastjson.JSONObject(result).toJSONString());
    }
    
    /**
     * 获取社区帖子列表
     * GET /api/community/posts.do
     */
    @RequestMapping("/posts.do")
    public void getCommunityPosts(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("[DEBUG] CommunityController.getCommunityPosts - 开始获取社区帖子列表");
        response.setContentType("application/json;charset=UTF-8");
        
        try {
            System.out.println("[DEBUG] CommunityController.getCommunityPosts - 调用communityService.getCommunityPosts()");
            List<CommunityPost> posts = communityService.getCommunityPosts();
            System.out.println("[DEBUG] CommunityController.getCommunityPosts - 获取到帖子列表，数量: " + (posts != null ? posts.size() : 0));
            
            Map<String, Object> data = new HashMap<>();
            data.put("posts", posts);
            
            Result.JSONResultMap result = Result.success(data);
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
            System.out.println("[DEBUG] CommunityController.getCommunityPosts - 响应发送成功");
            
        } catch (Exception e) {
            System.err.println("[ERROR] CommunityController.getCommunityPosts - 获取帖子列表失败: " + e.getMessage());
            e.printStackTrace();
            Result.JSONResultMap result = Result.error("获取帖子列表失败");
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
        }
    }
    
    /**
     * 获取帖子详情
     * GET /api/community/post/detail.do?id=1
     */
    @RequestMapping("/post/detail.do")
    public void getPostDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("[DEBUG] CommunityController.getPostDetail - 开始获取帖子详情");
        response.setContentType("application/json;charset=UTF-8");
        
        try {
            String idStr = request.getParameter("id");
            System.out.println("[DEBUG] CommunityController.getPostDetail - 请求参数 id: " + idStr);
            
            if (idStr == null || idStr.trim().isEmpty()) {
                System.err.println("[ERROR] CommunityController.getPostDetail - 帖子ID不能为空");
                Result.JSONResultMap result = Result.error("帖子ID不能为空");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                return;
            }
            
            int id = Integer.parseInt(idStr);
            System.out.println("[DEBUG] CommunityController.getPostDetail - 解析后的id: " + id);
            
            System.out.println("[DEBUG] CommunityController.getPostDetail - 调用communityService.getPostById()");
            CommunityPost post = communityService.getPostById(id);
            System.out.println("[DEBUG] CommunityController.getPostDetail - 获取到帖子详情: " + (post != null ? "成功" : "失败"));
            
            if (post == null) {
                System.err.println("[ERROR] CommunityController.getPostDetail - 帖子不存在，id: " + id);
                Result.JSONResultMap result = Result.error("帖子不存在");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                return;
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("post", post);
            
            Result.JSONResultMap result = Result.success(data);
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
            System.out.println("[DEBUG] CommunityController.getPostDetail - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] CommunityController.getPostDetail - 帖子ID格式错误: " + e.getMessage());
            Result.JSONResultMap result = Result.error("帖子ID格式错误");
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
        } catch (Exception e) {
            System.err.println("[ERROR] CommunityController.getPostDetail - 获取帖子详情失败: " + e.getMessage());
            e.printStackTrace();
            Result.JSONResultMap result = Result.error("获取帖子详情失败");
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
        }
    }
    
    /**
     * 创建新帖子
     * POST /api/community/post/create.do
     */
    @RequestMapping("/post/create.do")
    public void createPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("[DEBUG] CommunityController.createPost - 开始创建新帖子");
        response.setContentType("application/json;charset=UTF-8");
        
        try {
            // 读取请求体
            System.out.println("[DEBUG] CommunityController.createPost - 开始读取请求体");
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String jsonBody = sb.toString();
            System.out.println("[DEBUG] CommunityController.createPost - 请求体内容: " + jsonBody);
            
            Map<String, Object> requestData = com.alibaba.fastjson.JSON.parseObject(jsonBody, Map.class);
            System.out.println("[DEBUG] CommunityController.createPost - 解析后的请求数据: " + requestData);
            
            // 验证必填字段
            if (requestData == null) {
                System.err.println("[ERROR] CommunityController.createPost - 请求数据不能为空");
                Result.JSONResultMap result = Result.error("请求数据不能为空");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                return;
            }
            
            Integer userId = (Integer) requestData.get("userId");
            String title = (String) requestData.get("title");
            String content = (String) requestData.get("content");
            String images = (String) requestData.get("images");
            String videoUrl = (String) requestData.get("videoUrl");
            
            System.out.println("[DEBUG] CommunityController.createPost - 解析的字段 userId: " + userId + ", title: " + title + ", content: " + content + ", images: " + images + ", videoUrl: " + videoUrl);
            
            if (userId == null) {
                System.err.println("[ERROR] CommunityController.createPost - 用户ID不能为空");
                Result.JSONResultMap result = Result.error("用户ID不能为空");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                return;
            }
            
            if (title == null || title.trim().isEmpty()) {
                System.err.println("[ERROR] CommunityController.createPost - 标题不能为空");
                Result.JSONResultMap result = Result.error("标题不能为空");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                return;
            }
            
            if (content == null || content.trim().isEmpty()) {
                System.err.println("[ERROR] CommunityController.createPost - 内容不能为空");
                Result.JSONResultMap result = Result.error("内容不能为空");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                return;
            }
            
            // 创建帖子对象
            System.out.println("[DEBUG] CommunityController.createPost - 创建CommunityPost对象");
            CommunityPost post = new CommunityPost(userId, title, content, images, videoUrl);
            
            // 保存帖子
            System.out.println("[DEBUG] CommunityController.createPost - 调用communityService.createPost()");
            boolean success = communityService.createPost(post);
            System.out.println("[DEBUG] CommunityController.createPost - 创建帖子结果: " + (success ? "成功" : "失败"));
            
            if (success) {
                Result.JSONResultMap result = Result.success("帖子创建成功");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
                System.out.println("[DEBUG] CommunityController.createPost - 响应发送成功");
            } else {
                System.err.println("[ERROR] CommunityController.createPost - 帖子创建失败");
                Result.JSONResultMap result = Result.error("帖子创建失败");
                response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
            }
            
        } catch (Exception e) {
            System.err.println("[ERROR] CommunityController.createPost - 创建帖子失败: " + e.getMessage());
            e.printStackTrace();
            Result.JSONResultMap result = Result.error("创建帖子失败");
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(result));
        }
    }
} 